package com.lastproject.web.bean;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.ejb.EJB;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import com.lastproject.dto.AnswerDTO;
import com.lastproject.dto.QuestionDTO;
import com.lastproject.dto.QuestionOptionDTO;
import com.lastproject.dto.UserDTO;
import com.lastproject.ejb.dao.AnswerDAORemote;
import com.lastproject.ejb.dao.QuestionDAORemote;
import com.lastproject.ejb.dao.QuestionOptionDAORemote;

public class MySurveysBean {
	
	@EJB
	QuestionDAORemote questionDAO;
	@EJB
	QuestionOptionDAORemote questionOptionDAO;
	@EJB
	AnswerDAORemote answerDAO;
	
	private List<SurveyBeanAnswers> surveys;
	
	private SurveyBeanAnswers sb;

	public SurveyBeanAnswers getSb() {
		return sb;
	}

	public void setSb(SurveyBeanAnswers sb) {
		this.sb = sb;
	}
	
	/**
	 * Verifies if the current user has any surveys available for answering
	 * Valid surveys are does which don't have any answers recorded and their end date is in the future
	 * @return a boolean value true if any surveys are available for him and false otherwise
	 */
	public boolean isWithSurveys(){
		List<SurveyBeanAnswers> surveysAll = sb.getMySurveys();
		surveys = new ArrayList<>();
		FacesContext f = FacesContext.getCurrentInstance();
		UserDTO userDTO = (UserDTO) f.getExternalContext().getSessionMap().get("userDTO");
		boolean hasSurveys=false; 
		if(surveysAll!=null && !surveysAll.isEmpty()){
			for(SurveyBeanAnswers s:surveysAll)
				if(Calendar.getInstance().getTime().before(s.getSurveyDTO().getEndDate())){
					boolean valid=true;
					for(QuestionDTO q:questionDAO.getQuestionListBySurveyId(s.getSurveyDTO().getId()))
						for(QuestionOptionDTO qo:questionOptionDAO.getQuestionOptionListByQuestionId(q.getId())){
							for(AnswerDTO answer:answerDAO.getAnswersByQuestionOptionId(qo.getId()))
								if(answer.getIdUser()==userDTO.getId())
									valid=false;
							}
					if(valid){
						surveys.add(s);
						hasSurveys=true;
					}
				}
		}
		return hasSurveys;
	}

	public List<SurveyBeanAnswers> getSurveys() {
		return surveys;
	}

	public void setSurveys(List<SurveyBeanAnswers> surveys) {
		this.surveys = surveys;
	}

	/**
	 * calls the start method in the SurveyBean for displaying the selected survey
	 * @return 
	 * @param actionEvent because it is called by an actionListener
	 */
	public void start(ActionEvent actionEvent){
		int id = (int) actionEvent.getComponent().getAttributes().get("surveyId");
		sb.init(id);
	}
}
